package com.topisv.tms.task;

import java.util.concurrent.BlockingQueue;

import javax.persistence.OptimisticLockException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.OptimisticLockingFailureException;

import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.service.qimen.DeliveryOrderTaskService;
import com.topisv.tms.utils.enums.TaskStatus;

public class DeliveryOrderTaskWorker extends Thread {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private BlockingQueue<DeliveryOrderTask> tasks;
	private DeliveryOrderTaskService service;

	public DeliveryOrderTaskWorker(BlockingQueue<DeliveryOrderTask> tasks, DeliveryOrderTaskService service) {
		this.tasks = tasks;
		this.service = service;
	}

	@Override
	public void run() {
		while (true) {
			DeliveryOrderTask task = null;
			try {
				task = tasks.take();
				if (task != null) {
				    long t1 = System.currentTimeMillis();
				    service.dealData(task);
				    long t2 = System.currentTimeMillis();
				    logger.info("接单job处理耗时：task.id: {} ,订单转换处理时间：{} ms", task.getId(), t2 - t1);
				}
			} catch (Exception e) {
			    //add 20161025 取消单逻辑处理
			    if (e.getMessage() != null && e.getMessage().startsWith("接单job处理订单:DeliveryOrderTask不存在或者已被取消")) {
			        logger.info("接单job处理订单，任务已被取消单取消。DeliveryOrderTask.id:{}", task != null ? task.getId() : "null");
			        continue;
			    }
			    
				if(!(e.getCause() instanceof OptimisticLockException) && !(e instanceof OptimisticLockingFailureException)){
					logger.error(new StringBuilder("[").append(task != null ? task.getOrderNo() : null).append("]").append(" case some error.").toString(), e);
				}
				if (task != null) {
					if (task.getDealCount() >= 5) {
						logger.error("e:"+e.toString());
						if(e.toString().indexOf("Duplicate entry")>-1&&e.toString().indexOf("for key 'check_repeat'")>-1){
							task.setDealStatus(TaskStatus.Repeat.getStatus());
						}else{
							task.setDealStatus(TaskStatus.FAIL.getStatus());
						}
					} else {
						if(!(e.getCause() instanceof OptimisticLockException) && !(e instanceof OptimisticLockingFailureException)){
							task.setDealCount(task.getDealCount() + 1);
						}
						task.setDealStatus(TaskStatus.UNHAND.getStatus());
						task.setDealIp("-");
					}
					service.saveData(task);
				}
			}
		}
	}

}
